package com.gitee.l0km.thrift.swift2thrift.generator;

import java.util.List;

import com.gitee.l0km.codegen.annotations.CodegenDefaultvalue;
import com.gitee.l0km.codegen.annotations.CodegenInvalidValue;
import com.gitee.l0km.codegen.annotations.CodegenLength;
import com.gitee.l0km.codegen.annotations.CodegenRequired;
import com.gitee.l0km.xthrift.base.metadata.DecoratorThriftFieldMetadata;
import com.gitee.l0km.xthrift.base.metadata.ThriftFieldMetadataUtil;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableList;

public class CodegenExtDocument implements Function<DecoratorThriftFieldMetadata, List<String>> {

	public CodegenExtDocument() {
	}

	private String invalidValueComment(DecoratorThriftFieldMetadata input) {
		 CodegenInvalidValue ann = ThriftFieldMetadataUtil.extractFieldAnnotation(input,CodegenInvalidValue.class);
		if(ann != null){
			String iv = ann.value();
			if(iv.length() == 0){
				iv = ann.exp();
			}
			if(iv.length() > 0){
				return String.format("INVALID VALUE [%s] as null", iv);
			}
		}
		return null;
	}
	private String requiredComment(DecoratorThriftFieldMetadata input) {
		 CodegenRequired ann = ThriftFieldMetadataUtil.extractFieldAnnotation(input,CodegenRequired.class);
		if(ann != null && ann.value()){
			return "REQUIRED FIELD";
		}
		return null;
	}
	private String defaultvalueComment(DecoratorThriftFieldMetadata input) {
		 CodegenDefaultvalue ann = ThriftFieldMetadataUtil.extractFieldAnnotation(input,CodegenDefaultvalue.class);
		if(ann != null){
			return "DEFAULT VALUE :["+ ann.value() +"]";
		}
		return null;
	}
	private String lengthComment(DecoratorThriftFieldMetadata input) {
		CodegenLength ann = ThriftFieldMetadataUtil.extractFieldAnnotation(input,CodegenLength.class);
		int limit; 
		if(ann != null){
			if(ann.value() > 0){
				limit = ann.value();
				if(String.class.equals(input.getErpcType().getJavaType())){
					limit++;
				}
				return String.format("REQUIRED SIZE:%d", limit);
			}else if(ann.max() > 0){
				limit = ann.max();
				if(String.class.equals(input.getErpcType().getJavaType())){
					limit++;
				}
				return String.format("MAX  SIZE LIMIT:%d", limit);
			}
		}
		return null;
	}
	@Override
	public List<String> apply(DecoratorThriftFieldMetadata input) {
		ImmutableList.Builder<String>builder = ImmutableList.builder();
		String cmt;
		if((cmt = invalidValueComment(input)) != null){
			builder.add(cmt);
		}
		if((cmt = requiredComment(input)) != null){
			builder.add(cmt);
		}
		if((cmt = defaultvalueComment(input)) != null){
			builder.add(cmt);
		}
		if((cmt = lengthComment(input)) != null){
			builder.add(cmt);
		}
		return builder.build();
	}

}
